<style>
  .picImg {
    width: 40px;
    height: 40px;
  }
  .el-table thead {
    color: #333;
  }
</style>
<template>
  <div class="app-container">
    <!--&lt;!&ndash; 查询和其他操作 &ndash;&gt;-->
    <div class="filter-container">
      <el-form :inline="true" status-icon label-position="left" class="demo-form-inline" >
        <el-form-item label="联行号" prop="interBankNo">
          <el-input v-model="listQuery.interBankNo" placeholder="联行号"/>
        </el-form-item>
        <el-form-item label="银行名称" prop="bankName">
          <el-input v-model="listQuery.bankName" placeholder="银行名称"/>
        </el-form-item>
        <el-form-item label="所属省份" prop="isRead">
          <el-select v-model="listQuery.province" @change="filterQueryCity">
            <el-option v-for="item in cities" :key="item.label" :label="item.label"
                       :value="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属城市" prop="city">
          <el-select v-model="listQuery.city" placeholder="请选择">
            <el-option v-for="item in listQueryCities" :key="item.label" :label="item.label"
                       :value="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="银行地址" prop="address">
          <el-input v-model="listQuery.address" placeholder="银行地址"/>
        </el-form-item>
        <!-- <el-form-item label="所属区域编码" prop="districtCode">
          <el-input v-model="listQuery.districtCode" placeholder="所属区域编码"/>
        </el-form-item> -->
        <el-form-item>
          <el-button class="filter-item" type="primary" @click="queryList">查询</el-button>
          <el-button class="filter-item" type="primary" icon="el-icon-edit"
                 @click="handleAdd">新增
          </el-button>
          <el-button class="filter-item" type="primary" icon="el-icon-upload"
                     @click="handleExport">导入
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row
              :header-cell-style="{background:'#92D3FF',color:'#fff'}">

      <el-table-column align="center" min-width="100" label="联行号" prop="interBankNo"/>
      <el-table-column align="center" min-width="100" label="银行名称" prop="bankName"/>
      <el-table-column align="center" min-width="100" label="所属省份" prop="province"/>
      <el-table-column align="center" min-width="100" label="所属城市" prop="city"/>
      <el-table-column align="center" min-width="100" label="银行地址" prop="address"/>
      <!-- <el-table-column align="center" min-width="100" label="所属区域编码" prop="districtCode"/> -->
      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini"
                     @click="handleEdit(scope.row)">修改
          </el-button>
          <el-popover
            placement="top"
            width="200"
            trigger="manual"
            :ref="'popover-' + scope.row.interBankNo">
            <p>确定删除该数据吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-` + scope.row.interBankNo].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click="doDelete(scope.row)">确定</el-button>
            </div>
            <el-button type="danger" size="mini" slot="reference" @click="$refs[`popover-` + scope.row.interBankNo].doShow()">删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
                @pagination="getList"/>
    <!-- 新增编辑单对话框 -->
    <el-dialog :visible.sync="editDialogVisible" :title="textMap[dialogStatus]" :close-on-click-modal="false">
      <el-form ref="editForm" :rules="editFormRules" :model="editForm" status-icon label-position="left"
               label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="联行号" prop="interBankNo">
          <el-input :disabled="dialogStatus=='update'" v-model="editForm.interBankNo"/>
        </el-form-item>
        <el-form-item label="银行名称" prop="bankName">
          <el-input v-model="editForm.bankName" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="省城市" prop="provinceAndCity">
          <el-cascader
            :options="cities"
            v-model="editForm.provinceAndCity"
            :props="{ expandTrigger: 'hover',value:'label' }"
          ></el-cascader>
          <!--<el-input v-model="editForm.districtCode" auto-complete="off"/>-->
        </el-form-item>
        <el-form-item label="银行地址" prop="address">
          <el-input v-model="editForm.address" auto-complete="off"/>
        </el-form-item>
        <!-- <el-form-item label="所属区域编码" prop="districtCode">
          <el-input v-model="editForm.districtCode" auto-complete="off"/>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="doCreate">确定</el-button>
        <el-button v-else type="primary" @click="doEdit">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="exportDialogVisible" title="文件导入" :close-on-click-modal="false">
      <el-upload
        class="upload-demo"
        ref="upload"
        action="string"
        :before-upload="beforeUploadFile"
        :http-request="doUpload"
        :file-list="fileList"
        :limit="1"
        name="filename"
        :auto-upload="false">
        <el-button size="small" plain>选择文件</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xlsx(Excel2007)文件，且不超过10M</div>
        <!--<el-button slot="trigger" size="small" type="primary">选取文件</el-button>-->
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-left: 10px;" size="small" type="success" @click="exportDialogVisible=false">取消
        </el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="$refs.upload.submit()">确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { doGet, doPost, doFile } from '@/api'
  import { cities } from '@/utils/base'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

  const FETCH_PAGE = 'unionno.html'
  const FETCH_URL = {
    LIST: `${FETCH_PAGE}?op=list`,
    CREATE: `${FETCH_PAGE}?op=add`,
    EDIT: `${FETCH_PAGE}?op=chg`,
    DELETE: `${FETCH_PAGE}?op=del`,
    IMPORT: `${FETCH_PAGE}?op=import`
  }
  export default {
    name: 'bank',
    components: { Pagination },
    filters: {},
    data() {
      return {
        list: [],
        total: 0,
        listLoading: true,
        listQuery: {
          pageNum: 1,
          pageSize: 20,
          interBankNo: undefined,
          bankName: undefined,
          province: undefined,
          city: undefined,
          address: undefined,
          districtCode: undefined
        },
        listQueryCities:[],
        dialogStatus: undefined,
        textMap: {
          update: '编辑',
          create: '创建'
        },
        editForm: {
          bankCode: undefined,
          bankName: undefined,
          province: undefined,
          city: undefined,
          address: undefined,
          districtCode: undefined
        },
        editFormRules: {
          interBankNo: [{ required: true, message: '联行号不允许为空', trigger: 'blur' }],
          bankName: [{ required: true, message: '银行名称不允许为空', trigger: 'blur' }],
          provinceAndCity: [{ required: true, message: '省城市不允许为空', trigger: 'blur' }]
        },
        editDialogVisible: false,
        editIndex: undefined,
        cities: cities,
        exportDialogVisible: false,
        fileList: []
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        doGet(FETCH_URL.LIST, this.listQuery).then(response => {
          this.list = response.rows
          this.total = response.data.totalcount
          this.listLoading = false
        }).catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      },
      queryList(){
        this.listQuery.pageNum=1
        this.listQuery.pageSize=20
        this.getList()
      },
      filterQueryCity(){
        this.listQueryCities=[]
          console.log(this.listQuery.province)
          this.cities.map(item=>{
            if(item.label==this.listQuery.province){
                this.listQueryCities=item.children
            }
          })
      },
      /*===addBegin===*/
      handleAdd() {
        this.editForm = {
          interBankNo: undefined,
          bankName: undefined,
          province: undefined,
          city: undefined,
          address: undefined,
          districtCode: undefined
        }
        this.dialogStatus = 'create'
        this.editDialogVisible = true
        this.$nextTick(() => {
          this.$refs['editForm'].clearValidate()
        })
      },
      doCreate() {
        this.$refs['editForm'].validate(valid => {
          if (valid) {
            let sendData = {
              ...this.editForm,
              province: this.editForm.provinceAndCity[0],
              city: this.editForm.provinceAndCity[1]
            }
            doGet(FETCH_URL.CREATE, sendData
            )
              .then(response => {
                this.getList()
                this.editDialogVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.message
                })
              })
          }
        })
      },
      /*===addEnd===*/
      /*===editBegin===*/
      handleEdit(row) {
        this.editForm = Object.assign({}, row)
        this.editForm.provinceAndCity = [row.province, row.city]
        this.editIndex = this.list.indexOf(row)
        this.dialogStatus = 'update'
        this.editDialogVisible = true
        this.$nextTick(() => {
          this.$refs['editForm'].clearValidate()
        })
      },
      doEdit() {
        this.$refs['editForm'].validate(valid => {
          if (valid) {
            let sendData = {
              ...this.editForm,
              province: this.editForm.provinceAndCity[0],
              city: this.editForm.provinceAndCity[1]
            }
            doGet(FETCH_URL.EDIT, sendData)
              .then(response => {
                this.getList()
                this.editDialogVisible = false
                this.list[this.editIndex] = this.editForm
                this.$notify.success({
                  title: '成功',
                  message: '修改成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.message
                })
              })
          }
        })
      },
      /*==editEnd==*/
      /*==deleteBegin==*/
      doDelete(row) {
        doGet(FETCH_URL.DELETE, row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
            this.total--
            this.$refs[`popover-` + row.interBankNo].doClose()
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.message
            })
          })
      },
      /*==deleteEnd==*/
      /*==exportBegin==*/
      handleExport(value) {
        this.exportDialogVisible = true
      },
      beforeUploadFile(file) {
        console.log('before upload')
        console.log(file)
        let extension = file.name.substring(file.name.lastIndexOf('.')+1)
        let size = file.size / 1024 / 1024
        if(extension !== 'xlsx'&&extension !== 'xls') {
          this.$notify.warning({
            title: '警告',
            message: `只能上传Excel（即后缀是.xlsx或.xls）的文件`
          });
          return false
        }
        // if(size > 10) {
        //   this.$notify.warning({
        //     title: '警告',
        //     message: `文件大小不得超过10M`
        //   });
        // }
      },
      doUpload(param) {
        console.log('upload==>')
        let fd = new FormData()
        fd.append('filename', param.file)//传文件\
        doFile('unionno.html?op=import', fd).then((res)=> {
          this.getList()
          this.exportDialogVisible = false
          this.$notify.success({
            title: '成功',
            message: '上传成功'
          })
        }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.message
          })
        })
      }
      /*==exportEnd==*/
    }
  }
</script>
